package com.myProject.serves.Impl;

import com.myProject.bean.TInsect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myProject.dao.InsectDao;
import com.myProject.serves.InsectSev;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import util.SqlSessionUtil;

import java.io.InputStream;
import java.util.List;

public class InsectSevImpl implements InsectSev {
    @Override
    public List<TInsect> getInsectList(TInsect tInsect) {
        String config = "mybatis-configuration.xml";
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(config);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = factory.openSession();
        InsectDao id =  sqlSession.getMapper(InsectDao.class);
        List<TInsect>list =  id.getInsectList(tInsect);
        sqlSession.clearCache();
        return list;
    }

    @Override
    public PageInfo<TInsect> showInsectByPage(int pageNo, int pageSize, TInsect tInsect) {
        String config = "mybatis-configuration.xml";
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(config);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = factory.openSession();
        InsectDao insectMapper = sqlSession.getMapper(InsectDao.class);
        PageHelper.startPage(pageNo,pageSize);
        List<TInsect>list = insectMapper.getInsectList(tInsect);
        PageInfo<TInsect>page = new PageInfo<TInsect>(list);
        SqlSessionUtil.commit();
//       sqlSession.close();
        return page;
    }

    @Override
    public int addInsect(TInsect tInsect) {
        SqlSession sqlSession= SqlSessionUtil.getSqlSession();
        InsectDao insectMapper =  sqlSession.getMapper(InsectDao.class);
        int x = insectMapper.addInsect(tInsect);
        SqlSessionUtil.commit();
        sqlSession.close();
        return x;
    }
}
